package com.njupt.order.controller;

import com.njupt.common.pojo.CookieUtils;
import com.njupt.common.pojo.JsonUtils;
import com.njupt.common.pojo.TaotaoResult;
import com.njupt.order.pojo.OrderInfo;
import com.njupt.order.service.OrderService;
import com.njupt.pojo.TbItem;
import com.njupt.pojo.TbUser;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XJL
 * @Description:订单确认页面处理
 * @Date: Create in 14:42 2018/6/5
 * @Modified By:
 **/
@Controller
public class OrderCarController {

    @Value("${CART_KEY}")
    private String CART_KEY;
    @Autowired
    private OrderService orderService;

    /**
     * 展示订单确认页面
     * @param request
     * @return
     */
    @RequestMapping("/order/order-cart")
    public String showOrderCar(HttpServletRequest request){
        //用户必须是登陆状态
        //取用户ID
        TbUser user = (TbUser) request.getAttribute("user");
        System.out.println(user);
        //根据用户信息收货取收货地址列表,使用静态数据模拟
        //把地址信息传递给页面
        //从cookie中取购物车商品列表展示到页面
        List<TbItem> cartList = getCartList(request);

        //返回逻辑视图
        request.setAttribute("cartList",cartList);
        return "order-cart";
    }

    /**
     * 从Cookie获取商品列表
     * @param request
     * @return
     */
    private List<TbItem> getCartList(HttpServletRequest request) {
        String json = CookieUtils.getCookieValue(request, CART_KEY, true);
        if (json == null) {
            return new ArrayList<>();
        }
        List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
        return list;
    }

    /**
     * 生成订单
     * @param orderInfo
     * @return
     */
    @RequestMapping(value = "/order/create",method = RequestMethod.POST)
    public String createOrder(OrderInfo orderInfo,Model model){
       TaotaoResult result = orderService.createOrder(orderInfo);
       model.addAttribute("orderId",result.getData().toString());
       model.addAttribute("payment",orderInfo.getPayment());
       //收货时间
        DateTime dateTime = new DateTime();
        dateTime = dateTime.plusDays(3);
       model.addAttribute("date",dateTime.toString("yyyy-MM-dd"));
       return "success";
    }
}
